﻿using IPTools.Core;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.DependencyInjection;
using My.Core.Attributes;
using My.Core.Extensions;
using My.Framework;
using NLog;
using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;

namespace My.Core.Filters
{


	/// <summary>
	/// 操作日志过滤
	/// </summary>
	public class LogAttributeFilter : ActionFilterAttribute
	{
		static readonly Logger logger = LogManager.GetCurrentClassLogger();

		/// <summary>
		/// 日志标题
		/// </summary>
		public string Title { get; set; } = "";

		/// <summary>
		/// Action请求后，记录操作日志
		/// </summary>
		/// <param name="context"></param>
		public override void OnResultExecuted(ResultExecutedContext context)
		{
			if (context.ActionDescriptor is not ControllerActionDescriptor controllerActionDescriptor) return;

			int statusCode = context.HttpContext.Response.StatusCode;

			//获得注解信息
			LogAttribute logAttribute = GetLogAttribute(controllerActionDescriptor);
			if (logAttribute == null && statusCode != 403) return;

			try
			{
				string method = context.HttpContext.Request.Method.ToUpper();
				// 获取当前的用户
				string userName = context.HttpContext.GetName();
				string jsonResult = string.Empty;
				if (context.Result is ContentResult result && result.ContentType == "application/json")
				{
					jsonResult = result.Content.Replace("\r\n", "").Trim();
				}
				if (context.Result is JsonResult result2)
				{
					jsonResult = result2.Value?.ToString();
				}
				//获取当前执行方法的类名
				//string className =  System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;
				//获取当前成员的名称
				//string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
				string controller = context.RouteData.Values["Controller"].ToString();
				string action = context.RouteData.Values["Action"].ToString();

				string ip = HttpContextExtension.GetClientUserIp(context.HttpContext);
				var ip_info = IpTool.Search(ip);

				//SysOperLog sysOperLog = new()
				//{
				//    Status = 0,
				//    OperName = userName,
				//    OperIp = ip,
				//    OperUrl = HttpContextExtension.GetRequestUrl(context.HttpContext),
				//    RequestMethod = method,
				//    JsonResult = jsonResult,
				//    OperLocation = ip_info.Province + " " + ip_info.City,
				//    Method = controller + "." + action + "()",
				//    //Elapsed = _stopwatch.ElapsedMilliseconds,
				//    OperTime = DateTime.Now
				//};
				//HttpContextExtension.GetRequestValue(context.HttpContext, sysOperLog);

				//if (logAttribute != null)
				//{
				//    sysOperLog.Title = logAttribute?.Title;
				//    sysOperLog.BusinessType = (int)logAttribute?.BusinessType;
				//    sysOperLog.OperParam = logAttribute.IsSaveRequestData ? sysOperLog.OperParam : "";
				//    sysOperLog.JsonResult = logAttribute.IsSaveResponseData ? sysOperLog.JsonResult : "";
				//}

				if (statusCode == 403)
				{
					//sysOperLog.Status = 1;
					//sysOperLog.ErrorMsg = "无权限访问";
				}

				LogEventInfo ei = new(LogLevel.Info, "GlobalActionMonitor", "");

				ei.Properties["jsonResult"] = !HttpMethods.IsGet(method) ? jsonResult : "";
				//ei.Properties["requestParam"] = sysOperLog.OperParam;
				ei.Properties["user"] = userName;
				logger.Log(ei);

				//OperLogService.InsertOperlog(sysOperLog);
			}
			catch (Exception ex)
			{
				logger.Error(ex, $"记录操作日志出错了#{ex.Message}");
			}
		}

		private LogAttribute GetLogAttribute(ControllerActionDescriptor controllerActionDescriptor)
		{
			var attribute = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
				.FirstOrDefault(a => a.GetType().Equals(typeof(LogAttribute)));

			return (LogAttribute)attribute;
		}
	}
}
